function hfile = glm_RFX_RemovePredictors(hfile, removep)
% GLM::RFX_RemovePredictors  - removes predictors for each subject
%
% FORMAT:       [glm] = glm.RFX_RemovePredictors(removep)
%
% Input fields:
%
%       removep     specification of predictors to remove

% Version:  v0.7g
% Build:    9101518
% Date:     Oct-15 2009, 6:41 PM CEST
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% argument check
if nargin < 2 || ...
    numel(hfile) ~= 1 || ...
   ~isBVQXfile(hfile, 'glm') || ...
    isempty(removep) || ...
   (~isa(removep, 'double') && ...
    ~ischar(removep) && ...
    ~iscell(removep))
    error( ...
        'BVQXfile:BadArgument', ...
        'Invalid call to %s.', ...
        mfilename ...
    );
end
bc = bvqxfile_getcont(hfile.L);
if bc.ProjectTypeRFX ~= 1
    error( ...
        'BVQXfile:BadArgument', ...
        'Invalid call to %s.', ...
        mfilename ...
    );
end
nums = bc.NrOfSubjects;
nump = bc.NrOfSubjectPredictors;
if ~isa(removep, 'double')
    if ~iscell(removep)
        removep = {removep};
    end
    sp = glm_SubjectPredictors(hfile);
    for pc = numel(removep):-1:1
        if ~ischar(removep{pc}) || ...
           ~any(strcmpi(sp, removep{pc}(:)'))
            removep(pc) = [];
        else
            removep{pc} = findfirst(strcmpi(sp, removep{pc}(:)'));
        end
    end
    if isempty(removep)
        return;
    end
    removep = unique(cat(2, removep{:}));
    removep = removep(:)';
else
    removep = removep(:)';
    removep(isinf(removep) | isnan(removep) | removep < 1 | ...
        removep(:) ~= fix(removep(:)) | removep >= nump) = [];
    if isempty(removep)
        return;
    end
end

% build to-be-removed/-kept index variables
remi = false(1, nump - 1);
remi(removep) = true;
keepi = ~remi;
keepi(end+1) = true;
remi = repmat(remi, [1, nums]);
remi(end+1:numel(bc.Predictor)) = false;
nnump = sum(~remi) / nums;
if nnump ~= fix(nnump)
    error( ...
        'BVQXfile:InvalidObject', ...
        'Invalid object given.' ...
    );
end

% make changes
bc.NrOfSubjectPredictors = nnump;
bc.NrOfPredictors = sum(~remi);
bc.Predictor(remi) = [];

% rename predictor (Name1)
for pc = 1:numel(bc.Predictor)
    bc.Predictor(pc).Name1 = sprintf('Predictor: %d', pc);
end

% alter BetaMaps
switch (bc.ProjectType)
    case {0, 1}
        for sc = 1:nums
            bc.GLMData.Subject(sc).BetaMaps = ...
                bc.GLMData.Subject(sc).BetaMaps(:, :, :, keepi);
        end
    case {2}
        for sc = 1:nums
            bc.GLMData.Subject(sc).BetaMaps = ...
                bc.GLMData.Subject(sc).BetaMaps(:, keepi);
        end
    otherwise
        error( ...
            'BVQXfile:InvalidObject', ...
            'Invalid ProjectType setting in GLM.' ...
        );
end

% set back
bvqxfile_setcont(hfile.L, bc);
